<?php
set_time_limit(300000);
include_once('config.inc.php');
include_once('set_error_handling.php');

class AlbumArtExtraction
	{
/******************************************************************************************************************
-Used to Initialise variables.
/******************************************************************************************************************/		
		var $is_debug=0;
		var $path_symbol="/";
		var $album_art_folder="/home/search/public_html/mp3management/album_art";
/******************************************************************************************************************
-Class constructor. set path symbol to "/" if running on linux. set it to "\" if running on windows.
/******************************************************************************************************************/
		function AlbumArtExtraction()
			{
				$this->is_debug=0;
				$this->path_symbol="/";
				$this->album_art_folder="/home/search/public_html/mp3management/album_art";
			}
/******************************************************************************************************************
-Used to get album art from amazon.com.
/******************************************************************************************************************/			
		function GetAlbumArtFromAmazon()
			{				
				//Enter your Amazon Web Services IDs
				define("Access_Key_ID", "Access_Key_ID");
				define("Associate_tag", "Associate_tag");
				define("Amazon_secret_key", "Amazon_secret_key");
				$image_types=array('LARGEIMAGE','MEDIUMIMAGE','SMALLIMAGE');
						
				$select_str="SELECT distinct(album),artist FROM mp_id3_tags WHERE album_art='' and artist!='' and album!=''";
				$result=$this->safe_mysql_query($select_str);
				
				$counter=0;
				while($row=mysql_fetch_assoc($result))
					{
						$album=$row['album'];
						$artist=$row['artist'];
						
						$SearchIndex='Music';
						$Keywords=urlencode($artist.' '.$album);
						$Operation = "ItemSearch";
						$Version = "2007-07-16";
						$ResponseGroup = "ItemAttributes,Images";
						$request=
						     "http://ecs.amazonaws.com/onca/xml"
						   . "?Service=AWSECommerceService"
						   . "&AssociateTag=" . Associate_tag
						   . "&AWSAccessKeyId=" . Access_Key_ID
						   . "&Operation=" . $Operation
						   . "&Version=" . $Version
						   . "&SearchIndex=" . $SearchIndex
						   . "&Keywords=" . $Keywords
						   . "&ResponseGroup=" . $ResponseGroup;

						$request=$this->SignAmazonUrl($request,Amazon_secret_key);

						$response = file_get_contents($request);								
						xml_parse_into_struct(xml_parser_create(),$response,$value_array,$index_array);
						if(isset($index_array['SMALLIMAGE'])||isset($index_array['MEDIUMIMAGE'])||isset($index_array['LARGEIMAGE']))
							{			
								$image_url="";					
								for($count=0;$count<count($image_types);$count++)
									{
										if(!isset($index_array[$image_types[$count]]))continue;										
										$index=$index_array[$image_types[$count]][0]+1;
										if($value_array[$index]['tag']=='URL')
											{
												$image_url=$value_array[$index]['value'];
												break;
											}
										else continue;
									}
																	
								$index=strrpos($image_url,'/');
								$image_name=substr($image_url,$index+1);
								$image_name=mysql_escape_string(urldecode($image_name));
								
								$file_str=file_get_contents($image_url);
								$file_handle = fopen($this->album_art_folder.$this->path_symbol.$image_name, 'w');
								fwrite($file_handle, $file_str);
								fclose($file_handle);
								
								$update_str="UPDATE mp_id3_tags SET album_art='".$image_name."' WHERE album='".mysql_escape_string($album)."' AND artist='".mysql_escape_string($artist)."'";							
								$this->safe_mysql_query($update_str);
								$this->DebuggingMessage($image_name.'<br/>');
								$counter++;								
							}							
						sleep(1);
					}
				echo '<br/><br/>Number of images downloaded : '.$counter;
			}	
/******************************************************************************************************************
-Used to sign a url for amazon web services.
/******************************************************************************************************************/
function SignAmazonUrl($url,$amazon_secret_key)
	{
	    $CONFIG['AMAZON_SECRET_KEY']=$amazon_secret_key;

	    $original_url = $url;
	
	    // Decode anything already encoded
	    $url = urldecode($url);
	
	    // Parse the URL into $urlparts
	    $urlparts       = parse_url($url);
	
	    // Build $params with each name/value pair
	    foreach (split('&', $urlparts['query']) as $part) {
	        if (strpos($part, '=')) {
	            list($name, $value) = split('=', $part, 2);
	        } else {
	            $name = $part;
	            $value = '';
	        }
	        $params[$name] = $value;
	    }
	
	    // Include a timestamp if none was provided
	    if (empty($params['Timestamp'])) {
	        $params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
	    }
	
	    // Sort the array by key
	    ksort($params);
	
	    // Build the canonical query string
	    $canonical       = '';
	    foreach ($params as $key => $val) {
	        $canonical  .= "$key=".rawurlencode($val)."&";
	    }
	    // Remove the trailing ampersand
	    $canonical       = preg_replace("/&$/", '', $canonical);
	
	    // Some common replacements and ones that Amazon specifically mentions
	    $canonical       = str_replace(array(' ', '+', ',', ';'), array('%20', '%20', urlencode(','), urlencode(':')), $canonical);
	
	    // Build the si
	    $string_to_sign             = "GET\n{$urlparts['host']}\n{$urlparts['path']}\n$canonical";
	    // Calculate our actual signature and base64 encode it
	    $signature            = base64_encode(hash_hmac('sha256', $string_to_sign, $CONFIG['AMAZON_SECRET_KEY'], true));
	
	    // Finally re-build the URL with the proper string and include the Signature
	    $url = "{$urlparts['scheme']}://{$urlparts['host']}{$urlparts['path']}?$canonical&Signature=".rawurlencode($signature);
	    return $url;
	}
/******************************************************************************************************************
-Used to display a message on the browser.
/******************************************************************************************************************/
		function DebuggingMessage($message)
			{				
				if($this->is_debug)echo $message;
				flush();
			}
/******************************************************************************************************************
-Used to execute the specified query.
/******************************************************************************************************************/
		function safe_mysql_query($SQLquery) 
			{
				$result = @mysql_query($SQLquery);
				if (mysql_error()) 
					{
						die('<FONT COLOR="red">'.mysql_error().'</FONT><hr><TT>'.$SQLquery.'</TT>');
					}
				return $result;
			}			
/***************************************************************************************************************************************/
	}
?>